<template>
  <div class="create-campaign-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">众筹平台</h1>
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">首页</el-menu-item>
            <el-menu-item index="/campaigns">众筹列表</el-menu-item>
            <el-menu-item index="/create">创建众筹</el-menu-item>
            <el-menu-item index="/my-campaigns">我的众筹</el-menu-item>
          </el-menu>
          <div class="user-info">
            <span class="username">{{ user.username }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <div class="create-container">
          <el-card class="create-card">
            <div slot="header" class="card-header">
              <h2>创建众筹项目</h2>
              <p>填写以下信息来创建您的众筹项目</p>
            </div>

            <el-alert
              v-if="!walletConnected"
              title="提示"
              type="warning"
              description="请先连接钱包以创建众筹项目"
              show-icon
              :closable="false"
              style="margin-bottom: 20px;"
            >
              <el-button type="primary" size="small" @click="connectWallet">
                连接钱包
              </el-button>
            </el-alert>

            <el-form
              v-if="walletConnected"
              :model="form"
              :rules="rules"
              ref="createForm"
              label-width="120px"
              class="create-form"
            >
              <el-form-item label="项目名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入项目名称"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="项目描述" prop="description">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="5"
                  placeholder="请详细描述您的项目"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="筹款目标" prop="goal">
                <el-input
                  v-model="form.goal"
                  placeholder="请输入筹款目标"
                  type="number"
                  step="0.001"
                >
                  <template slot="append">ETH</template>
                </el-input>
              </el-form-item>

              <el-form-item label="持续时间" prop="duration">
                <el-row :gutter="10">
                  <el-col :span="16">
                    <el-input
                      v-model="form.duration"
                      type="number"
                      placeholder="请输入持续时间"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-select v-model="form.timeUnit" placeholder="时间单位" style="width: 100%">
                      <el-option label="分钟" :value="2"></el-option>
                      <el-option label="小时" :value="1"></el-option>
                      <el-option label="天" :value="0"></el-option>
                    </el-select>
                  </el-col>
                </el-row>
                <div class="form-tip">
                  结束时间：{{ endTime }}
                </div>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  :loading="creating"
                  @click="handleCreate"
                  size="large"
                >
                  创建众筹
                </el-button>
                <el-button @click="resetForm" size="large">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card class="tips-card">
            <div slot="header">
              <h3>创建提示</h3>
            </div>
            <ul class="tips-list">
              <li>
                <i class="el-icon-info"></i>
                项目名称应简洁明了，能够准确概括项目内容
              </li>
              <li>
                <i class="el-icon-info"></i>
                项目描述应详细说明项目的目标、用途和计划
              </li>
              <li>
                <i class="el-icon-info"></i>
                筹款目标应合理设置，建议根据实际需求确定
              </li>
              <li>
                <i class="el-icon-info"></i>
                持续时间建议设置为 7-30 天，给予支持者足够的考虑时间
              </li>
              <li>
                <i class="el-icon-warning"></i>
                创建众筹需要支付一定的 Gas 费用
              </li>
              <li>
                <i class="el-icon-warning"></i>
                众筹创建后，如果没有人投资，可以取消；否则无法取消
              </li>
              <li>
                <i class="el-icon-success"></i>
                达到目标后，您可以提取所有筹集的资金
              </li>
              <li>
                <i class="el-icon-error"></i>
                未达到目标，支持者可以申请退款
              </li>
            </ul>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import contractService from '@/api/contract';

export default {
  name: 'CreateCampaign',
  data() {
    return {
      user: {},
      walletConnected: false,
      form: {
        name: '',
        description: '',
        goal: '',
        duration: '',
        timeUnit: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
          { min: 3, max: 100, message: '项目名称长度在 3 到 100 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入项目描述', trigger: 'blur' },
          { min: 10, max: 500, message: '项目描述长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        goal: [
          { required: true, message: '请输入筹款目标', trigger: 'blur' },
          { validator: this.validateGoal, trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入持续时间', trigger: 'blur' },
          { validator: this.validateDuration, trigger: 'blur' }
        ]
      },
      creating: false,
      activeMenu: '/create'
    };
  },
  computed: {
    endTime() {
      if (!this.form.duration || !this.form.timeUnit && this.form.timeUnit !== 0) {
        return '-';
      }
      
      const duration = parseInt(this.form.duration);
      if (isNaN(duration) || duration <= 0) {
        return '-';
      }
      
      const now = new Date();
      let endDate = new Date(now);
      
      switch(this.form.timeUnit) {
        case 0: // 天
          endDate.setDate(now.getDate() + duration);
          break;
        case 1: // 小时
          endDate.setHours(now.getHours() + duration);
          break;
        case 2: // 分钟
          endDate.setMinutes(now.getMinutes() + duration);
          break;
      }
      
      return endDate.toLocaleString('zh-CN');
    }
  },
  created() {
    this.loadUserInfo();
    this.checkWalletConnection();
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    },
    
    async checkWalletConnection() {
      if (web3Helper.getAccount()) {
        this.walletConnected = true;
      }
    },
    
    async connectWallet() {
      try {
        await web3Helper.connect();
        this.walletConnected = true;
        await contractService.init();
        this.$message.success('钱包连接成功！');
      } catch (error) {
        this.$message.error(error.message || '钱包连接失败');
      }
    },
    
    validateGoal(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入筹款目标'));
      } else {
        const goal = parseFloat(value);
        if (isNaN(goal) || goal <= 0) {
          callback(new Error('筹款目标必须大于 0'));
        } else {
          callback();
        }
      }
    },
    
    validateDuration(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入持续时间'));
      } else {
        const duration = parseInt(value);
        if (isNaN(duration) || duration <= 0) {
          callback(new Error('持续时间必须大于 0'));
        } else {
          const timeUnit = this.form.timeUnit;
          if (timeUnit === 0 && duration > 365) {
            callback(new Error('持续时间不能超过 365 天'));
          } else if (timeUnit === 1 && duration > 8760) {
            callback(new Error('持续时间不能超过 8760 小时'));
          } else if (timeUnit === 2 && duration > 525600) {
            callback(new Error('持续时间不能超过 525600 分钟'));
          } else {
            callback();
          }
        }
      }
    },
    
    handleCreate() {
      this.$refs.createForm.validate(async (valid) => {
        if (valid) {
          this.creating = true;
          try {
            await contractService.init();
            
            await contractService.launchCampaign(
              this.form.name,
              this.form.description,
              this.form.goal,
              parseInt(this.form.duration),
              this.form.timeUnit
            );
            
            this.$message.success('众筹创建成功！');
            
            // 跳转到我的众筹页面
            setTimeout(() => {
              this.$router.push('/my-campaigns');
            }, 1500);
          } catch (error) {
            console.error('创建众筹失败:', error);
            this.$message.error(error.message || '创建众筹失败');
          } finally {
            this.creating = false;
          }
        }
      });
    },
    
    resetForm() {
      this.$refs.createForm.resetFields();
    },
    
    handleMenuSelect(index) {
      this.$router.push(index);
    },
    
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user');
        web3Helper.disconnect();
        this.$message.success('已退出登录');
        this.$router.push('/login');
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.create-campaign-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  font-size: 24px;
  color: #409EFF;
  margin: 0;
  margin-right: 40px;
}

.nav-menu {
  flex: 1;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: bold;
  color: #333;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.create-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.create-card,
.tips-card {
  height: fit-content;
}

.card-header h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.card-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.create-form {
  margin-top: 20px;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.tips-card h3 {
  margin: 0;
  color: #333;
}

.tips-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tips-list li {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  color: #666;
  line-height: 1.6;
}

.tips-list li:last-child {
  border-bottom: none;
}

.tips-list li i {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .create-container {
    grid-template-columns: 1fr;
  }
}
</style>

